import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Login from '@/views/login'
import Register from '@/views/register'
import Collect from '@/views/collect'
import Detail from '@/views/detail'
import Rent from '@/views/rent'
import City from '@/views/city'
import Search from '@/views/search'
import SearchCommunity from '@/views/searchCommunity'
import Map from '@/views/map'
import AddHouse from '@/views/addHouse'
import Home from '@/views/home'
import Find from '@/views/find'
import News from '@/views/news'
import My from '@/views/my'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'
Vue.use(Toast)
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/find',
        component: Find
      },
      {
        path: '/news',
        component: News
      },
      {
        path: '/my',
        component: My
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/collect',
    component: Collect
  },
  {
    path: '/detail/:houseCode',
    component: Detail
  },
  {
    path: '/rent',
    component: Rent
  },
  {
    path: '/addHouse',
    component: AddHouse
  },
  {
    path: '/city/:currentCity',
    component: City
  },
  {
    path: '/search/:city',
    component: Search
  },
  {
    path: '/searchCommunity/:value',
    component: SearchCommunity
  },
  {
    path: '/map',
    component: Map
  }
]

const router = new VueRouter({
  routes
})

// 解决报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// 全局前置守卫
const whiteList = ['/login', '/register', '/home', '/my']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      Toast('宝贝，请先登录哦~~~')
      setTimeout(() => {
        next('/login')
      }, 500)
    }
  }
})

export default router
